/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 8.3下午3.c
> Author:
> Mail:
> Created Time: Sun 04 Aug 2024 04:37:56 AM PDT
***************************************************/

// 利用匿名管道实现，父进程给子进程发送一个学员信息，子收到后显示
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
typedef struct student
{
    int code;
    char name[10];
    int age;
} STU;
int main()
{
    STU *buf = malloc(sizeof(STU));
    memset(buf, 0, sizeof(STU));
    int fd[2] = {0};
    int ret = 0;
    pid_t pid = 0;

    ret = pipe(fd);       //创建管道
    if (ret == -1)
    {
        perror("pipe");
        exit(-1);
    }

    pid = fork();
    if (pid == 0)
    {
        close(fd[1]);
        ret = read(fd[0], buf, sizeof(STU));
        if (ret == -1)
        {
            perror("read");
            exit(-1);
        }
        printf("学号:%d\n", buf->code);
        printf("姓名:%s\n", buf->name);
        printf("年龄:%d\n", buf->age);
        close(fd[0]);

        exit(0);
    }
    else if (pid < 0)
    {
        printf("fork error\n");
    }

    close(fd[0]);
    printf("请输入学生学号:\n");
    scanf("%d", &buf->code);
    printf("请输入学生年龄:\n");
    scanf("%d", &buf->age);
    printf("请输入学生姓名:\n");
    scanf("%s", buf->name);
    ret = write(fd[1], buf, sizeof(STU));
    if (ret == -1)
    {
        perror("write");
        exit(-1);
    }

    wait(NULL);
    close(fd[1]);
    free(buf);
    return 0;
}
